<template>
    <v-col style="flex: none; width: 300px;">
        <v-card class="fill-height d-flex flex-column" flat color="surface">
            <!-- 操作按钮 -->
            <v-container fluid class="py-2 px-3">
                <v-row dense justify="space-around">
                    <v-col cols="4" class="text-center">
                        <div @click="showAddFriendDialog = true"
                            class="d-flex flex-column align-center text-caption cursor-pointer"
                            :class="showAddFriendDialog ? 'text-primary font-weight-bold tab-bounce' : 'text-medium-emphasis'"
                            style="transition: color 0.2s">
                            <v-icon size="28" class="mb-1">mdi-plus</v-icon>
                            添加好友
                        </div>
                    </v-col>
                    <v-col cols="4" class="text-center">
                        <div @click="showJoinGroupDialog = true"
                            class="d-flex flex-column align-center text-caption cursor-pointer"
                            :class="showJoinGroupDialog ? 'text-primary font-weight-bold tab-bounce' : 'text-medium-emphasis'"
                            style="transition: color 0.2s">
                            <v-icon size="28" class="mb-1">mdi-plus</v-icon>
                            加入群组
                        </div>
                    </v-col>
                    <v-col cols="4" class="text-center">
                        <div @click="openFriendRequestDialog"
                            class="d-flex flex-column align-center text-caption cursor-pointer"
                            :class="showFriendRequestDialog ? 'text-primary font-weight-bold tab-bounce' : 'text-medium-emphasis'"
                            style="transition: color 0.2s">
                            <v-icon size="28" class="mb-1">mdi-account-multiple-check</v-icon>
                            好友申请
                        </div>
                    </v-col>
                </v-row>
            </v-container>

            <!-- 聊天列表 -->
            <v-container fluid class="pa-0 scroll-area">
                <ChatListItem v-for="chat in filteredChatList" :key="chat.id + '-' + chat.type" :chat="chat"
                    :selected="chat.id === selectedChat?.id && chat.type === selectedChat?.type"
                    @click="() => $emit('select', chat)" class="mb-1" />
            </v-container>

        </v-card>

        <!-- 添加好友对话框 -->
        <v-dialog v-model="showAddFriendDialog" max-width="400">
            <v-card>
                <v-card-title>添加好友</v-card-title>
                <v-card-text>
                    <v-text-field label="对方用户ID" v-model="friendUserId" type="number" clearable />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn text @click="showAddFriendDialog = false">取消</v-btn>
                    <v-btn color="primary" @click="sendAddFriendRequest">发送请求</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>

        <!-- 加入群组对话框 -->
        <v-dialog v-model="showJoinGroupDialog" max-width="400">
            <v-card>
                <v-card-title>加入群组</v-card-title>
                <v-card-text>
                    <v-text-field label="群组ID" v-model="groupId" type="number" clearable />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn text @click="showJoinGroupDialog = false">取消</v-btn>
                    <v-btn color="primary" @click="sendJoinGroupRequest">加入</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>

        <!-- 好友申请对话框 -->
        <v-dialog v-model="showFriendRequestDialog" max-width="500">
            <v-card>
                <v-card-title class="text-h6">好友申请</v-card-title>
                <v-card-text>
                    <div v-if="loadingRequests" class="text-center text-medium-emphasis">加载中...</div>
                    <div v-else-if="friendRequests.length === 0" class="text-center text-medium-emphasis">暂无好友申请</div>
                    <v-container v-else class="pa-0">
                        <v-card v-for="req in friendRequests" :key="req.requestId" class="mb-3" outlined elevation="1">
                            <v-card-title>
                                {{ req.senderName }} (ID: {{ req.senderId }})
                            </v-card-title>
                            <v-card-subtitle class="pb-2">{{ formatTime(req.createdAt) }}</v-card-subtitle>
                            <v-card-actions>
                                <v-spacer />
                                <v-btn small color="primary" @click="acceptFriendRequest(req.requestId)">接受</v-btn>
                                <v-btn small color="error" @click="rejectFriendRequest(req.requestId)">拒绝</v-btn>
                            </v-card-actions>
                        </v-card>
                    </v-container>
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn text @click="showFriendRequestDialog = false">关闭</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-col>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { useChatStore } from '@/stores/sessions';

const props = defineProps<{
    chatList: any[]
    selectedChat: any
    chooseTab: string
}>()


defineEmits(['select'])

const showAddFriendDialog = ref(false)
const showJoinGroupDialog = ref(false)
const showFriendRequestDialog = ref(false)

const friendUserId = ref<number | null>(null)
const groupId = ref<number | null>(null)
const currentUserId = Number(localStorage.getItem('user_id'))
const token = localStorage.getItem('jwt_token')

const friendRequests = ref<any[]>([])
const loadingRequests = ref(false)

const filteredChatList = computed(() => {
    return props.chatList.filter(chat => {
        if (props.chooseTab === 'friends') return chat.type === 'friends'
        else return chat.type === 'group'
    })
})

async function sendAddFriendRequest() {
    if (!friendUserId.value || !currentUserId) return
    try {
        await axios.post(
            'http://localhost:8080/api/friends/send',
            null,
            {
                params: {
                    senderId: currentUserId,
                    receiverId: friendUserId.value,
                },
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            }
        )
        alert('✅ 好友请求已发送')
        showAddFriendDialog.value = false
    } catch (err) {
        console.error('❌ 添加好友失败', err)
        alert('❌ 添加好友失败')
    }
}

async function sendJoinGroupRequest() {
    if (!groupId.value || !currentUserId) return
    try {
        await axios.post(
            `http://localhost:8080/api/chatroom/${groupId.value}/join`,
            null,
            {
                params: { userId: currentUserId },
                headers: { Authorization: `Bearer ${token}` },
                auth: { username: 'admin', password: '123456' },
            }
        )
        alert('✅ 加入群组成功')
        showJoinGroupDialog.value = false
        await useChatStore().loadChatList()
    } catch (err) {
        console.error('❌ 加入群组失败', err)
        alert('❌ 加入群组失败')
    }
}

async function openFriendRequestDialog() {
    showFriendRequestDialog.value = true
    loadingRequests.value = true
    try {
        const res = await axios.get(
            `http://localhost:8080/api/friends/getApply/${currentUserId}`,
            {
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            }
        )
        friendRequests.value = res.data
    } catch (err) {
        console.error('❌ 获取好友申请失败', err)
        friendRequests.value = []
    } finally {
        loadingRequests.value = false
    }
}

function formatTime(datetime: string): string {
    const date = new Date(datetime)
    return date.toLocaleString()
}

async function acceptFriendRequest(requestId: string) {
    try {
        await axios.post(
            `http://localhost:8080/api/friends/accept`,
            null,
            {
                params: { requestId },
                headers: { Authorization: `Bearer ${token}` },
            }
        )
        alert('✅ 已接受好友请求')
        friendRequests.value = friendRequests.value.filter((r) => r.requestId !== requestId)
        await useChatStore().loadChatList()
    } catch (err) {
        console.error('❌ 接受好友请求失败', err)
        alert('❌ 接受好友请求失败')
    }
}

async function rejectFriendRequest(requestId: string) {
    try {
        await axios.post(
            `http://localhost:8080/api/friends/reject`,
            null,
            {
                params: { requestId },
                headers: { Authorization: `Bearer ${token}` }
            }
        )
        alert('✅ 已拒绝好友请求')
        friendRequests.value = friendRequests.value.filter((r) => r.requestId !== requestId)
    } catch (err) {
        console.error('❌ 拒绝好友请求失败', err)
        alert('❌ 拒绝好友请求失败')
    }
}

</script>

<style scoped>
.tab-bounce {
    animation: tabBounce 300ms ease;
}

@keyframes tabBounce {
    0% {
        transform: scale(1);
    }

    40% {
        transform: scale(0.9);
    }

    100% {
        transform: scale(1);
    }
}
</style>
